package com.example.ykbboom.universitytransportation.Activity;

import android.content.Intent;
import android.content.res.ColorStateList;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.Marker;
import com.example.ykbboom.universitytransportation.R;
import com.example.ykbboom.universitytransportation.Service.RequestAcceptService;
import com.example.ykbboom.universitytransportation.Util.LogUtil;
import com.example.ykbboom.universitytransportation.Util.NetUtil;
import com.example.ykbboom.universitytransportation.Util.SharedPrefUtil;
import com.example.ykbboom.universitytransportation.Util.ToastUtil;

/**
 * @author ykbboom
 * @email ykbpro@whut.edu.cn
 * @time 2017-1-25 22:05:04
 * 功能: 主界面
*/
public class MainActivity extends BaseActivity implements LocationSource,
        AMapLocationListener,AMap.OnMarkerClickListener,AMap.OnInfoWindowClickListener {

    /**private static final int STROKE_COLOR = Color.argb(180, 3, 145, 255);
    private static final int FILL_COLOR = Color.argb(10, 0, 0, 180);*/
    private static final String TAG = MainActivity.class.getSimpleName();

    private Toolbar mToolbar;
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mDrawerToggle;
    private NavigationView mNavigationView;
    private MapView mMapView;//绘制地图视图
    private AMap aMap;//地图控制器
    private AMapLocationClient mLocationClient;//声明AMapLocationClient类对象
    private AMapLocationClientOption mLocationClientOption;
    private OnLocationChangedListener mOnLocationChangedListener;
    private Intent intent;
    private long clickTime = 0;
    private TextView phoneText;
    private TextView nameText;
    private TextView identityText;
    private View headerLayout;
    private String[]markerTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initMapView(savedInstanceState);
        /**
         * 使用通知
         * */
//        Intent intent = new Intent(this,MainActivity.class);
//        NotificationUtil.getNotification(intent,MainActivity.this);
    }
    @Override
    public void initView() {

        Intent serviceIntent = new Intent(this, RequestAcceptService.class);
        startService(serviceIntent);

        mToolbar = (Toolbar) findViewById(R.id.main_toolbar);
        setSupportActionBar(mToolbar);
        ActionBar actionBar = getSupportActionBar();
        if(actionBar!=null){
            actionBar.setDisplayHomeAsUpEnabled(true);//显示HomeAsUp按钮
            actionBar.setDisplayShowTitleEnabled(false);//不自动显示标题
        }
        mNavigationView = (NavigationView) findViewById(R.id.nav_view);
        headerLayout = mNavigationView.inflateHeaderView(R.layout.nav_header);
        phoneText = (TextView) headerLayout.findViewById(R.id.nav_header_phoneText);
        phoneText.setText(SharedPrefUtil.getUserPhone());
        nameText = (TextView) headerLayout.findViewById(R.id.nav_header_nameText);
        nameText.setText(SharedPrefUtil.getUserName());
        identityText = (TextView) headerLayout.findViewById(R.id.nav_header_identityText);
        if (!SharedPrefUtil.getDriverState()){
            identityText.setText("游客");
        }else{
            identityText.setText("车主");
        }
        mDrawerLayout = (DrawerLayout) findViewById(R.id.main_drawerlayout);
        //创建返回键，并实现打开关/闭监听,抽屉效果
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.open, R.string.close) {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
            }
            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
            }
        };
        mDrawerToggle.syncState();
        mDrawerLayout.addDrawerListener(mDrawerToggle);

        ColorStateList colorStateList= ContextCompat.getColorStateList(this,R.color.nav_menu_item_color);
        mNavigationView.setItemTextColor(colorStateList);
        mNavigationView.setItemIconTintList(null);
        mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()){
                    case R.id.nav_settings:
                        intent = new Intent(MainActivity.this,SettingActivity.class);
                        startActivity(intent);
                        break;
                    case R.id.nav_my_request:
                        intent = new Intent(MainActivity.this,MyRequestActivity.class);
                        startActivity(intent);
                        break;
                    case R.id.nav_become_master:
                        intent = new Intent(MainActivity.this,BecomeDriverActivity.class);
                        startActivity(intent);
                        break;
                    case R.id.nav_record:
                        intent = new Intent(MainActivity.this,MyOrderActivity.class);
                        startActivity(intent);
                        break;
                }
                return true;
            }
        });
    }
    /**
     * 绘制地图及定位监听
     * */
    private void initMapView(Bundle savedInstanceState){
        //获取地图控件引用
        mMapView = (MapView) findViewById(R.id.map);
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
        mMapView.onCreate(savedInstanceState);
        if (aMap == null) {
            aMap = mMapView.getMap();
        }
        initAMap(aMap);


    }
    /**
     * 初始化AMap对象
     * */
    private void initAMap(AMap aMap){
        // 设置定位监听
        aMap.setLocationSource(this);
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        // 设置为true表示显示定位层，可触发定位显示当前位置
        aMap.setMyLocationEnabled(true);
        // 设置定位的类型为定位模式，有定位、跟随或地图根据面向方向旋转几种
        aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_FOLLOW);
        //隐藏缩放按钮
        aMap.getUiSettings().setZoomControlsEnabled(true);
        //设置缩放按钮的位置
        aMap.getUiSettings().setZoomPosition(AMapOptions.ZOOM_POSITION_RIGHT_BUTTOM);
        //setupLocationStyle();
        //aMap.setOnMarkerClickListener(this);//响应点击marker
        aMap.setOnInfoWindowClickListener(this);//响应点击InfoWindow
    }
    /**
     * 改变定位样式及范围
     *
    private void setupLocationStyle(){
        // 自定义系统定位蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        // 自定义定位蓝点图标
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.
                fromResource(R.drawable.gps_point));
        // 自定义精度范围的圆形边框颜色
        myLocationStyle.strokeColor(STROKE_COLOR);
        //自定义精度范围的圆形边框宽度
        myLocationStyle.strokeWidth(5);
        // 设置圆形的填充颜色
        myLocationStyle.radiusFillColor(FILL_COLOR);
        // 将自定义的 myLocationStyle 对象添加到地图上
        aMap.setMyLocationStyle(myLocationStyle);
    }*/

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar_menu_main,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.publish_request:
                intent = new Intent(this,PublishRequestActivity.class);
                startActivity(intent);
                break;
            case R.id.show_order_list_btn:
                intent = new Intent(this,ShowAroundOrderActivity.class);
                startActivity(intent);
                break;
            default:
        }
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
    }
    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
        deactivate();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (!SharedPrefUtil.getDriverState()){
            identityText.setText("游客");
        }else{
            identityText.setText("车主");
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mMapView.onDestroy();
        //销毁AMapLocationClient
        if(null != mLocationClient){
            mLocationClient.onDestroy();
        }
    }
    /**
     * 设置定位参数
     * */
    private AMapLocationClientOption getAMapLocationClientOption(){
        //设置发起定位的模式和相关参数
        AMapLocationClientOption mLocationClientOption = new AMapLocationClientOption();
        mLocationClientOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mLocationClientOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mLocationClientOption.setHttpTimeOut(30000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mLocationClientOption.setInterval(10000);//可选，设置定位间隔。默认为2秒
        mLocationClientOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
        mLocationClientOption.setOnceLocation(false);//可选，设置是否单次定位。默认是false
        mLocationClientOption.setOnceLocationLatest(true);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        mLocationClientOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
        mLocationClientOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mLocationClientOption.setLocationCacheEnable(true); //可选，设置是否使用缓存定位，默认为true
        return mLocationClientOption;
    }
    /**
     * 定位成功后回调函数
     * 在回调方法中调用“mOnLocationChangedListener.onLocationChanged(amapLocation);”可以在地图上显示系统小蓝点。
     * */
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (mOnLocationChangedListener != null && aMapLocation != null) {
            if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
                mOnLocationChangedListener.onLocationChanged(aMapLocation);// 显示系统小蓝点
                LogUtil.i(TAG,aMapLocation.getCity()+","+aMapLocation.getLatitude()+","+aMapLocation.getLongitude());
                LogUtil.i(TAG,"定位成功回调");

                SharedPrefUtil.saveUserCity(aMapLocation.getCity());
                SharedPrefUtil.saveUserLatlong(String.valueOf(aMapLocation.getLatitude())+","+String.valueOf(aMapLocation.getLongitude()));
                aMap.moveCamera(CameraUpdateFactory.zoomTo(16));//设置地图缩放比例

                NetUtil.aroundSearch(SharedPrefUtil.getUserPhone(),SharedPrefUtil.getUserLatlong(),String.valueOf(SharedPrefUtil.getCheckDistance()),aMap);

            } else {
                LogUtil.e(TAG,"定位失败,"+aMapLocation.getErrorCode()+":"+aMapLocation.getErrorInfo());
            }
        }
    }
    /**
     * InfoWindow点击事件
     * */
    @Override
    public void onInfoWindowClick(Marker marker) {
        markerTitle = marker.getTitle().split(":");
        NetUtil.getRequestDetail(markerTitle[1],this);
    }
    /**
     * Marker点击事件
     * */
    @Override
    public boolean onMarkerClick(Marker marker) {
        if (aMap!=null){
            marker.showInfoWindow();
        }
        return true;
    }

    /**
     * 激活定位
     * */
    @Override
    public void activate(OnLocationChangedListener listener) {
        mOnLocationChangedListener = listener;
        if(mLocationClient==null){
            //初始化定位
            mLocationClient = new AMapLocationClient(this);
            mLocationClient.setLocationListener(this);
            mLocationClientOption = getAMapLocationClientOption();
            mLocationClient.setLocationOption(mLocationClientOption);

        }
        /**
         *此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
         *注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
         *在定位结束后，在合适的生命周期调用onDestroy()方法
         *在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
         * */
        mLocationClient.startLocation();
    }
    /**
     * 停止定位
     * */
    @Override
    public void deactivate() {
        mOnLocationChangedListener = null;
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
        mLocationClient = null;
    }

    /**
     * 点击两次后退退出程序
     * */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit() {
        if ((System.currentTimeMillis() - clickTime) > 2000) {
            ToastUtil.showToast(this,"再按一次后退键退出程序");
            clickTime = System.currentTimeMillis();
        } else {
            LogUtil.i(TAG, "退出程序");
            this.finish();
            System.exit(0);
        }
    }
}
